package org.dromara.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.dromara.admin.domain.ProductCategory;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.admin.service.IProductService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.ProductGroupBo;
import org.dromara.admin.domain.vo.ProductGroupVo;
import org.dromara.admin.domain.ProductGroup;
import org.dromara.admin.mapper.ProductGroupMapper;
import org.dromara.admin.service.IProductGroupService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 产品分组Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProductGroupServiceImpl implements IProductGroupService {

    private final ProductGroupMapper baseMapper;
    private final IProductService productService;
    private final IEmployeeService employeeService;

    /**
     * 查询产品分组
     *
     * @param id 主键
     * @return 产品分组
     */
    @Override
    public ProductGroupVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询产品分组列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品分组分页列表
     */
    @Override
    public TableDataInfo<ProductGroupVo> queryPageList(ProductGroupBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProductGroup> lqw = buildQueryWrapper(bo);
        Page<ProductGroupVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前用户的公司产品分组列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品分组分页列表
     */
    @Override
    public TableDataInfo<ProductGroupVo> queryPageMyList(ProductGroupBo bo, PageQuery pageQuery) {
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());

        bo.setCompanyId(employeeVo.getCompanyId()); // 重新赋值主体id
        LambdaQueryWrapper<ProductGroup> lqw = buildQueryWrapper(bo);
        Page<ProductGroupVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的产品分组列表
     *
     * @param bo 查询条件
     * @return 产品分组列表
     */
    @Override
    public List<ProductGroupVo> queryList(ProductGroupBo bo) {
        LambdaQueryWrapper<ProductGroup> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ProductGroup> buildQueryWrapper(ProductGroupBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ProductGroup> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ProductGroup::getSort).orderByDesc(ProductGroup::getId);
        lqw.eq(bo.getCompanyId() != null, ProductGroup::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getGroupName()), ProductGroup::getGroupName, bo.getGroupName());
        return lqw;
    }

    /**
     * 新增产品分组
     *
     * @param bo 产品分组
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProductGroupBo bo) {
        ProductGroup add = MapstructUtils.convert(bo, ProductGroup.class);
        // 查询登录用户的主体信息
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        add.setCompanyId(employeeVo.getCompanyId());
        // 检验同一公司下的分类名称是否重复
        validateUniqueName(add);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 校验分组名称是否重复
     */
    private void validateUniqueName(ProductGroup add) {
        LambdaQueryWrapper<ProductGroup> wrapper = new LambdaQueryWrapper<ProductGroup>()
            .eq(ProductGroup::getGroupName, add.getGroupName())
            .eq(ProductGroup::getCompanyId, add.getCompanyId());
        if (add.getId() != null) {
            wrapper.ne(ProductGroup::getId, add.getId());
        }
        if (baseMapper.exists(wrapper)) {
            throw new ServiceException("同一公司下分组名称不能重复！");
        }
    }

    /**
     * 修改产品分组
     *
     * @param bo 产品分组
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductGroupBo bo) {
        ProductGroup update = MapstructUtils.convert(bo, ProductGroup.class);
        // 检验同一公司下的分类名称是否重复
        validateUniqueName(update);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProductGroup entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品分组信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            if (CollUtil.isEmpty(ids)) {
                throw new ServiceException("请选择需要删除的分组！");
            }

            List<ProductGroupVo> productGroupVoList = baseMapper.selectVoByIds(ids);
            if (CollUtil.isEmpty(productGroupVoList)) {
                throw new ServiceException("分组不存在或已被删除！");
            }

            EmployeeVo employeeVo = employeeService.queryById(LoginHelper.getUserId());
            Long companyId = employeeVo.getCompanyId(); // 获取登录用户的主体id

            // 检验是否属于当前公司
            List<String> invalidNames = productGroupVoList.stream()
                .filter(c -> !Objects.equals(c.getCompanyId(), companyId))
                .map(ProductGroupVo::getGroupName)
                .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(invalidNames)) {
                throw new ServiceException("无权删除以下分组（非本公司所属）：" + String.join("、", invalidNames));
            }

            // 校验是否存在产品（该分组下是否有关联的产品）
            List<Long> hasProductGroupIds = productService.getGroupIdsWithProducts(ids); // 查询分组下有产品的分组id
            if (CollUtil.isNotEmpty(hasProductGroupIds)) {
                List<String> groupNames = productGroupVoList.stream()
                    .filter(c -> hasProductGroupIds.contains(c.getId()))
                    .map(ProductGroupVo::getGroupName)
                    .collect(Collectors.toList());
                throw new ServiceException("以下分组下有产品，请先删除产品：" + String.join("、", groupNames));
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
